const mongoose = require('mongoose')

mongoose.connect('mongodb://127.0.0.1:27017/bilibili').then(() => {
  console.log('准备使用')
}).catch(error => {
  console.log('初始连接错误', error)
})

mongoose.connection.on('error', error => {
  console.log('初始连接后错误', error)
})

mongoose.connection.on('disconnected', () => {
  console.log('失去连接错误')
})

mongoose.connection.on('connected', () => {
  console.log('连接成功connected')
})

mongoose.connection.once('open', () => { 
  console.log('连接成功open')

  const schema = new mongoose.Schema({
    name: {
      type: String,
      required: true,
      unique: true,
    },
    author: {
      type: String,
      default: '佚名',
    },
    price: Number,
    status: {
      type: String,
      enum: ['上架', '下架'],
    },
    is_hot: Boolean,
    tags: Array,
    create_time: Date,
    notes: mongoose.Schema.Types.Mixed,
  })

  // book单词书写为单数时，在数据库创建集合时会自动变为复数books
  const module = mongoose.model('book', schema)

  // module.deleteOne({ _id: '6822fce3559560e755c04176' }).then(data => {
  //   console.log('删除成功', data)
  // }).catch(error => {
  //   console.log('删除失败', error)
  // })

  // module.deleteMany({ is_hot: false }).then(data => {
  //   console.log('删除成功', data)
  // }).catch(error => {
  //   console.log('删除失败', error)
  // })

})

mongoose.connection.on('close', () => {
  console.log('连接关闭')
})

mongoose.connection.on('reconnected', () => {
  console.log('重连成功')
})

// setTimeout(() => {
//   mongoose.disconnect()
// }, 5000)